'''This module takes an educated guess and where a user is from.'''
############################################################################
#    Copyright (C) 2006 by Robert Small                                    #
#    SmallR2002@Gmail.com                                                  #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

__module_name__        = "bcgeoip"
__module_version__     = "0.0.1"
__module_description__ = "This module takes an educated guess and where a user is from."

import xchat
import sys
import os
import sqlite3
import socket

if (sys.path.count(os.path.dirname(__file__) ) == 0):
    sys.path.append(os.path.dirname(__file__) )

#  Pretty much essential.
import bcsettings
import bcmisc

def getlocation_old(ip):
    curs = con.cursor()
    curs.execute("SELECT * FROM MMGIP_GeoData WHERE (BeginNum <= ?) AND (EndNum >= ?)", (ip, ip,))
    try:
        rows = curs.fetchall()
        if len(rows) > 0:
            return rows[0][5]
        else:
            return "Unknown"
    except:
        return "Unknown"

def getlocation(ip):
    curs = con.cursor()
    curs.execute("SELECT * FROM MMGeoIP WHERE (Low <= ?) AND (High >= ?)", (ip, ip,))
    try:
        rows = curs.fetchall()
        if len(rows) > 0:
            return rows[0][2]
        else:
            return "Unknown"
    except:
        return "Unknown"

def iptonum(ip):
    splittemp = ip.split(".")
    return str(int(splittemp[3]) + (int(splittemp[2]) * 256) + (int(splittemp[1]) * 256 * 256) + (int(splittemp[0]) * 256 * 256 * 256))

def isip(data):
    splittemp = data.split(".")
    if len(splittemp) == 4:
        for s in splittemp:
            try:
                n = int(s)
                if n < 0 and n > 255:
                    return False
            except ValueError:
                return False
        return True
    else:
        return False

def gethost(data):
    try:
        temp = socket.gethostbyname(data)
    except:
        return ""
    return temp

def checktld(data):
    pass


def join_location_check(word, word_eol, userdata): #IGNORE:W0613
    temp = word[2][word[2].find("@")+1:]
    if temp[:5] == "webtv": temp = temp[5:]
    if temp[:6] == "msntv2": temp = temp[7:]
    if isip(temp):
        # Woo, it's an IP, let us commence parting.
        location = getlocation(iptonum(temp))
        xchat.prnt("\x0302GeoIP locate on " + word[0] + " says they're in: " + location + "\x03")
        return xchat.EAT_NONE
    
    temp = gethost(temp)
    if len(temp) > 0: location = getlocation(iptonum(temp))
    if len(temp) > 0 and location != "Unknown":
        xchat.prnt("\x0302GeoIP locate on " + word[0] + " says they're in: " + location + " (" + temp + ")\x03")
        return xchat.EAT_NONE
    else:
        s =  word[2][word[2].find("@")+1:]
        tails = bcmisc.hostendings
        temp2 = [res for (res, tail) in tails.iteritems() if s.endswith(tail)]
        #max(tails, key=lambda k: len(os.path.commonprefix((s[::-1], tails[k][::-1]))))
        if len(temp2) > 0:
            location = temp2[0]
            if len(temp) > 0:
                xchat.prnt("\x0302GeoIP locate on " + word[0] + " says they're in: " + location + " (" + temp + ")\x03")
            else:
                xchat.prnt("\x0302GeoIP locate on " + word[0] + " says they're in: " + location + "\x03")
        else:
            if len(temp) > 0:
                xchat.prnt("\x0302GeoIP locate on " + word[0] + " does not seem to be able to resolve. (" + temp + ")\x03")
            else:
                xchat.prnt("\x0302GeoIP locate on " + word[0] + " does not seem to be able to resolve.\x03")
    
    #<SmallR2002> >>> s = "TZ-4B937B95.il-chicago0.sa.earthlink.net"
    #<SmallR2002> >>> tails = {"Chicago, IL, USA": ".il-chicago0.sa.earthlink.net", "United States": "earthlink.net", "Somewhere beyond the vortex": ".net"}
    #<SmallR2002> >>> [res for (res, tail) in tails.iteritems() if s.endswith(tail)]
    
con = sqlite3.connect(bcsettings.sqlite_database)